<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;

class Up
{
    protected $order;
    protected $set;
    protected $user;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->set = SetUserUp::getLastOne();
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        // 报单区
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            $this->upPrice();
        }

    }

    public function upPrice()
    {
        $amount = $this->order->total_pay - $this->order->total_freight;

        $is_up = false;

        // 分公司
        if ($amount == $this->set->svip3) {
            if ($this->user->level < UserLevel::$keys['svip3']) {
                $this->user->level = UserLevel::$keys['svip3'];
                $this->user->save();
            }
            $is_up = true;
        }
        // 总代
        else if ($amount == $this->set->svip2) {
            if ($this->user->level < UserLevel::$keys['svip2']) {
                $this->user->level = UserLevel::$keys['svip2'];
                $this->user->save();
            }
            $is_up = true;
        }
        // 经销商
        else if ($amount == $this->set->svip1) {
            if ($this->user->level < UserLevel::$keys['svip1']) {
                $this->user->level = UserLevel::$keys['svip1'];
                $this->user->save();
            }
            $is_up = true;
        }
        // 会员
        else if ($amount == $this->set->vip1) {
            if ($this->user->level < UserLevel::$keys['vip1']) {
                $this->user->level = UserLevel::$keys['vip1'];
                $this->user->save();
            }
            $is_up = true;
        }

        // 推荐2人升级svip
        if ($is_up) {
            $r = Chain::getReferrer($this->user->id, true);
            if ($r && $r->level == UserLevel::$keys['vip1']) {
                $children = (int)User::find()
                    ->where(['referrer_id' => $r->id])
                    ->andWhere(['>=', 'level', UserLevel::$keys['vip1']])
                    ->count();
                if ($children >= $this->set->vip2) {
                    $r->level = UserLevel::$keys['vip2'];
                    $r->save();
                }
            }
        }
    }

}